import {
  changeModal,
  getAdminUserAsync,
} from "@/store/adminUser/adminUserSlice";
import { useAppDispatch, useAppSelector } from "@/store/hooks";
import { Form, Input, Modal, Select } from "antd";
import { useEffect, useState, type ReactElement } from "react";
import { create, update } from "@/store/adminUser/adminUserAPI";

export default function Create(): ReactElement<typeof Modal, "div"> {
  const [loading, setLoading] = useState<boolean>(false);
  const { modal, params } = useAppSelector((state) => state.adminUser);
  const {
    config: { data: { data: { admin_permission = [] } = {} } = {} } = {},
  } = useAppSelector((state) => state.app);
  const dispatch = useAppDispatch();
  const [form] = Form.useForm();

  const handleClose = () => {
    dispatch(changeModal({ open: false }));
    form.resetFields();
  };

  const handleOk = async () => {
    try {
      const values = await form.validateFields();
      setLoading(true);
      if (modal.type === "create") {
        create({
          username: values.username,
          password: values.password,
          account_permission: values.account_permission,
        })
          .then(() => {
            handleClose();
            dispatch(getAdminUserAsync({ ...params }));
          })
          .finally(() => setLoading(false));
      } else if (modal.type === "update") {
        update({
          db_id: modal.record?.id as number,
          account_permission: values.account_permission,
        })
          .then(() => {
            handleClose();
            dispatch(getAdminUserAsync({ ...params }));
          })
          .finally(() => setLoading(false));
      }
    } catch (err) {
      console.log("校验不通过");
    }
  };

  useEffect(() => {
    if(modal.open && modal.type === 'update'){
      form.setFieldsValue(modal.record)
    }
  }, [modal])
  
  return (
    <Modal
      open={modal.open}
      title={modal.type === "create" ? "创建" : "编辑"}
      onCancel={handleClose}
      onOk={handleOk}
      confirmLoading={loading}
    >
      <Form form={form}>
        <Form.Item
          name="username"
          rules={[{ required: true, message: "必填" }]}
          label="账号"
        >
          <Input disabled={modal.type === 'update'} />
        </Form.Item>
        <Form.Item
          name="password"
          rules={[{ required: true, message: "必填" }]}
          label="密码"
        >
          <Input disabled={modal.type === 'update'} />
        </Form.Item>
        <Form.Item
          name="account_permission"
          rules={[{ required: true, message: "必填" }]}
          label="权限"
        >
          <Select options={admin_permission} />
        </Form.Item>
      </Form>
    </Modal>
  );
}
